import os

import fitz
from PIL import Image


def image_to_pdf(url):
    """
    图片转pdf
    :param url: 图片文件路径
    :return:
    """
    dir_name = os.path.basename(url)
    doc = fitz.open()
    img_doc = fitz.open(url)
    pdf = img_doc.convert_to_pdf()
    pdf_doc = fitz.open('pdf', pdf)
    doc.insert_pdf(pdf_doc)
    doc.save(dir_name.split('.')[0] + '.pdf')
    doc.close()


def pdf_to_image(url):
    """
    pdf转图片
    :param url: pdf文件路径
    :return:
    """
    with fitz.open(url) as pdf:
        print(pdf.page_count)
        for page in pdf:
            pm = page.get_pixmap()
            pm.save('page-%i.png' % page.number)


def merge_pdf(url):
    """
    多pdf合并
    :param url: pdf文件所在文佳夹
    :return:
    """
    exists = os.path.exists(url)
    basename = os.path.basename(url)
    list_pdf = []
    if not exists:
        print(url + '文件夹不存在')
    else:
        listdir = os.listdir(url)
        for file in listdir:
            file_base_name = os.path.basename(file)
            if not file_base_name.endswith('.pdf'):
                print(file + '不是pdf文件')
                continue
            else:
                list_pdf.append(file)
        if len(list_pdf) <= 0:
            print('不存在pdf文件')
        else:
            doc = fitz.open()
            for pdf in list_pdf:
                pdf = url + '\\' + pdf
                pdf_doc = fitz.open(pdf)
                doc.insert_pdf(pdf_doc)
            file_name = basename + '.pdf'
            doc.save(file_name)
            doc.close()


def merge_img(url):
    """
    多图片合并
    :param url: 图片文佳夹链接
    :return:
    """
    ims = [Image.open(url + '\\' + fn) for fn in os.listdir(url) if fn.endswith('.png')]  # 打开路径下的所有图片
    width, height = ims[0].size
    result = Image.new(ims[0].mode, (width, height * len(ims)))
    for j, im in enumerate(ims):
        result.paste(im, box=(0, j * height))
        print(j)
    result.save('%s.png' % 'merge_1')
